// 成就系统
class AchievementSystem {
    constructor() {
        this.achievements = {};
        this.unlockedAchievements = new Set();
        this.init();
    }

    init() {
        // 定义所有成就
        this.defineAchievements();
        
        // 加载已解锁的成就
        this.loadUnlockedAchievements();
        
        // 绑定事件
        this.bindEvents();
    }

    defineAchievements() {
        this.achievements = {
            first_choice: {
                id: 'first_choice',
                titleKey: 'achievement_first_choice',
                descKey: 'achievement_first_choice_desc',
                icon: '🎯',
                category: 'progress',
                hidden: false
            },
            scientist: {
                id: 'scientist',
                titleKey: 'achievement_scientist', 
                descKey: 'achievement_scientist_desc',
                icon: '🔬',
                category: 'playstyle',
                hidden: false
            },
            explorer: {
                id: 'explorer',
                titleKey: 'achievement_explorer',
                descKey: 'achievement_explorer_desc', 
                icon: '🚀',
                category: 'playstyle',
                hidden: false
            },
            survivor: {
                id: 'survivor',
                titleKey: 'achievement_survivor',
                descKey: 'achievement_survivor_desc',
                icon: '🛡️',
                category: 'playstyle', 
                hidden: false
            },
            all_endings: {
                id: 'all_endings',
                titleKey: 'achievement_all_endings',
                descKey: 'achievement_all_endings_desc',
                icon: '👑',
                category: 'completion',
                hidden: false
            },
            // 隐藏成就
            speed_reader: {
                id: 'speed_reader',
                titleKey: 'achievement_speed_reader',
                descKey: 'achievement_speed_reader_desc',
                icon: '⚡',
                category: 'hidden',
                hidden: true
            },
            perfectionist: {
                id: 'perfectionist', 
                titleKey: 'achievement_perfectionist',
                descKey: 'achievement_perfectionist_desc',
                icon: '💎',
                category: 'hidden',
                hidden: true
            }
        };

        // 添加隐藏成就的翻译
        if (window.i18n) {
            window.i18n.addTranslations('zh', {
                achievement_speed_reader: '闪电阅读者',
                achievement_speed_reader_desc: '在最快文字速度下完成游戏',
                achievement_perfectionist: '完美主义者', 
                achievement_perfectionist_desc: '不使用存档完成所有结局'
            });

            window.i18n.addTranslations('en', {
                achievement_speed_reader: 'Speed Reader',
                achievement_speed_reader_desc: 'Complete the game at maximum text speed',
                achievement_perfectionist: 'Perfectionist',
                achievement_perfectionist_desc: 'Complete all endings without loading saves'
            });
        }
    }

    loadUnlockedAchievements() {
        const saved = localStorage.getItem('timeecho_achievements');
        if (saved) {
            try {
                const achievementArray = JSON.parse(saved);
                this.unlockedAchievements = new Set(achievementArray);
            } catch (error) {
                console.error('加载成就数据失败:', error);
                this.unlockedAchievements = new Set();
            }
        }
    }

    saveUnlockedAchievements() {
        const achievementArray = Array.from(this.unlockedAchievements);
        localStorage.setItem('timeecho_achievements', JSON.stringify(achievementArray));
    }

    bindEvents() {
        // 监听语言切换事件
        window.addEventListener('languageChanged', () => {
            this.updateAchievementDisplay();
        });
    }

    unlock(achievementId) {
        if (!this.achievements[achievementId]) {
            console.warn(`未知成就ID: ${achievementId}`);
            return false;
        }

        if (this.unlockedAchievements.has(achievementId)) {
            return false; // 已经解锁
        }

        // 解锁成就
        this.unlockedAchievements.add(achievementId);
        this.saveUnlockedAchievements();

        // 显示解锁通知
        this.showUnlockNotification(achievementId);

        // 触发解锁事件
        window.dispatchEvent(new CustomEvent('achievementUnlocked', {
            detail: { achievementId, achievement: this.achievements[achievementId] }
        }));

        return true;
    }

    showUnlockNotification(achievementId) {
        const achievement = this.achievements[achievementId];
        if (!achievement) return;

        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = 'achievement-notification slide-in-right';
        notification.innerHTML = `
            <div class="achievement-notification-content">
                <div class="achievement-icon">${achievement.icon}</div>
                <div class="achievement-info">
                    <div class="achievement-unlock-text">${window.i18n.get('achievementUnlocked')}</div>
                    <div class="achievement-title">${window.i18n.get(achievement.titleKey)}</div>
                    <div class="achievement-desc">${window.i18n.get(achievement.descKey)}</div>
                </div>
            </div>
        `;

        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, rgba(0, 212, 255, 0.9), rgba(78, 205, 196, 0.9));
            color: white;
            padding: 15px;
            border-radius: 12px;
            min-width: 300px;
            z-index: 1001;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
        `;

        // 添加内部样式
        const style = document.createElement('style');
        style.textContent = `
            .achievement-notification-content {
                display: flex;
                align-items: center;
                gap: 12px;
            }
            .achievement-icon {
                font-size: 24px;
                flex-shrink: 0;
            }
            .achievement-info {
                flex: 1;
            }
            .achievement-unlock-text {
                font-size: 12px;
                opacity: 0.9;
                margin-bottom: 4px;
            }
            .achievement-title {
                font-weight: 600;
                font-size: 14px;
                margin-bottom: 2px;
            }
            .achievement-desc {
                font-size: 12px;
                opacity: 0.8;
            }
        `;

        document.head.appendChild(style);
        document.body.appendChild(notification);

        // 播放解锁音效（如果启用）
        this.playUnlockSound();

        // 5秒后移除通知
        setTimeout(() => {
            notification.style.animation = 'slideOutRight 0.3s ease-in forwards';
            setTimeout(() => {
                notification.remove();
                style.remove();
            }, 300);
        }, 5000);
    }

    playUnlockSound() {
        const soundEnabled = document.getElementById('soundEnabled')?.checked !== false;
        if (soundEnabled) {
            // 这里可以播放音效，但为了符合比赛要求（无外部API调用），我们使用简单的Web Audio API
            try {
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const oscillator = audioContext.createOscillator();
                const gainNode = audioContext.createGain();

                oscillator.connect(gainNode);
                gainNode.connect(audioContext.destination);

                oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
                oscillator.frequency.setValueAtTime(1000, audioContext.currentTime + 0.1);
                oscillator.frequency.setValueAtTime(1200, audioContext.currentTime + 0.2);

                gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);

                oscillator.start(audioContext.currentTime);
                oscillator.stop(audioContext.currentTime + 0.3);
            } catch (error) {
                // 忽略音频播放错误
                console.log('音效播放失败，可能浏览器不支持');
            }
        }
    }

    isUnlocked(achievementId) {
        return this.unlockedAchievements.has(achievementId);
    }

    getUnlockedCount() {
        return this.unlockedAchievements.size;
    }

    getTotalCount() {
        return Object.keys(this.achievements).length;
    }

    getUnlockedPercentage() {
        return Math.round((this.getUnlockedCount() / this.getTotalCount()) * 100);
    }

    getAllAchievements() {
        return Object.values(this.achievements);
    }

    getAchievementsByCategory(category) {
        return Object.values(this.achievements).filter(achievement => 
            achievement.category === category
        );
    }

    displayAchievements() {
        const achievementsList = document.getElementById('achievementsList');
        if (!achievementsList) return;

        achievementsList.innerHTML = '';

        // 按类别组织成就
        const categories = {
            progress: '进度成就',
            playstyle: '游戏风格',
            completion: '完成度',
            hidden: '隐藏成就'
        };

        Object.keys(categories).forEach(category => {
            const categoryAchievements = this.getAchievementsByCategory(category);
            if (categoryAchievements.length === 0) return;

            // 对于隐藏成就，只显示已解锁的
            const visibleAchievements = category === 'hidden' 
                ? categoryAchievements.filter(achievement => this.isUnlocked(achievement.id))
                : categoryAchievements;

            if (visibleAchievements.length === 0) return;

            // 创建类别标题
            const categoryTitle = document.createElement('h3');
            categoryTitle.textContent = window.i18n.getCurrentLanguage() === 'zh' 
                ? categories[category] 
                : category.charAt(0).toUpperCase() + category.slice(1);
            categoryTitle.style.cssText = `
                grid-column: 1 / -1;
                color: var(--primary-color);
                margin: 20px 0 10px 0;
                font-size: 18px;
                border-bottom: 1px solid rgba(255, 255, 255, 0.2);
                padding-bottom: 5px;
            `;
            achievementsList.appendChild(categoryTitle);

            // 显示该类别的成就
            visibleAchievements.forEach(achievement => {
                const achievementElement = this.createAchievementElement(achievement);
                achievementsList.appendChild(achievementElement);
            });
        });

        // 显示总体进度
        this.displayProgress();
    }

    createAchievementElement(achievement) {
        const isUnlocked = this.isUnlocked(achievement.id);
        
        const element = document.createElement('div');
        element.className = `achievement-item ${isUnlocked ? 'unlocked' : 'locked'}`;
        
        element.innerHTML = `
            <div class="achievement-icon">${achievement.icon}</div>
            <div class="achievement-info">
                <div class="achievement-title">${window.i18n.get(achievement.titleKey)}</div>
                <div class="achievement-desc">${window.i18n.get(achievement.descKey)}</div>
                ${isUnlocked ? '<div class="achievement-status">✓ 已解锁</div>' : '<div class="achievement-status">🔒 未解锁</div>'}
            </div>
        `;

        // 添加样式
        if (!isUnlocked) {
            element.style.opacity = '0.6';
            element.style.filter = 'grayscale(50%)';
        }

        return element;
    }

    displayProgress() {
        // 在成就页面顶部显示总体进度
        const container = document.querySelector('.achievements-container');
        if (!container) return;

        let progressElement = container.querySelector('.achievement-progress');
        if (!progressElement) {
            progressElement = document.createElement('div');
            progressElement.className = 'achievement-progress';
            container.insertBefore(progressElement, container.querySelector('h2').nextSibling);
        }

        const percentage = this.getUnlockedPercentage();
        const unlockedCount = this.getUnlockedCount();
        const totalCount = this.getTotalCount();

        progressElement.innerHTML = `
            <div class="progress-info">
                <span>成就进度: ${unlockedCount}/${totalCount} (${percentage}%)</span>
            </div>
            <div class="progress-bar">
                <div class="progress-fill" style="width: ${percentage}%"></div>
            </div>
        `;

        progressElement.style.cssText = `
            margin: 20px 0;
            padding: 15px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        `;

        // 添加进度条样式
        const style = document.createElement('style');
        style.textContent = `
            .progress-info {
                text-align: center;
                margin-bottom: 10px;
                color: var(--text-primary);
                font-weight: 500;
            }
            .progress-bar {
                width: 100%;
                height: 8px;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 4px;
                overflow: hidden;
            }
            .progress-fill {
                height: 100%;
                background: linear-gradient(90deg, var(--primary-color), var(--accent-color));
                border-radius: 4px;
                transition: width 0.5s ease;
            }
            .achievement-item .achievement-icon {
                font-size: 20px;
                margin-right: 12px;
            }
            .achievement-item .achievement-info {
                flex: 1;
            }
            .achievement-item .achievement-status {
                font-size: 12px;
                margin-top: 5px;
                opacity: 0.8;
            }
            .achievement-item {
                display: flex;
                align-items: center;
            }
        `;

        if (!document.querySelector('#achievement-styles')) {
            style.id = 'achievement-styles';
            document.head.appendChild(style);
        }
    }

    updateAchievementDisplay() {
        // 当语言切换时更新显示
        if (document.getElementById('achievementsScreen').classList.contains('active')) {
            this.displayAchievements();
        }
    }

    // 检查特殊成就
    checkSpecialAchievements() {
        // 检查速度阅读成就
        if (window.gameEngine && window.gameEngine.textSpeed === 5) {
            const gameState = window.gameEngine.getGameState();
            if (gameState.flags.endings && gameState.flags.endings.length > 0) {
                this.unlock('speed_reader');
            }
        }

        // 检查完美主义者成就（这个需要更复杂的逻辑来跟踪是否使用了存档）
        // 暂时简化为完成所有结局
        if (window.gameEngine) {
            const gameState = window.gameEngine.getGameState();
            if (gameState.flags.endings && gameState.flags.endings.length >= 6) {
                this.unlock('perfectionist');
            }
        }
    }

    reset() {
        this.unlockedAchievements.clear();
        this.saveUnlockedAchievements();
    }
}

// 创建全局成就系统实例
window.achievementSystem = new AchievementSystem();